<!DOCTYPE html>
<html lang="en">
<head>
    <title>three.js webgl - glTF loader</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
    <link type="text/css" rel="stylesheet" href="./css/main.css?2=1">
    <script src="js/jquery-3.5.1.min.js"></script>
</head>

<body style="background: #fff">
<iframe src="menu.html"
        class="curifrme"
        frameborder="none"
></iframe>
<style>
    .color{
        background: #130AF2;
        width: 30px;
        height: 30px;
        border-radius: 4px;
        margin: 10px;
    }
</style>
<div style="position: absolute; top: 0px;right:10px">
    <div class="color" style="background:#E8C279" ></div>
    <div class="color" style="background:#130AF2 " ></div>
    <div class="color" style="background:#C5B49A " ></div>
    <div class="color" style="background:#6A5ACD " ></div>
    <div class="color" style="background:#AA4631 " ></div>
</div>


<script type="module">

    import * as THREE from './build/three.module.js';

    import Stats from './threejs/jsm/libs/stats.module.js';
    // 制作一个地板
    import { EffectComposer } from './threejs/jsm/postprocessing/EffectComposer.js';
    import { RenderPass } from './threejs/jsm/postprocessing/RenderPass.js';
    import { OutlinePass  } from './threejs/jsm/postprocessing/OutlinePass.js';
    import {PlaneGeometry, MeshPhongMaterial, Mesh} from './build/three.module.js';
    import { OrbitControls } from './threejs/jsm/controls/OrbitControls.js';
    import { GLTFLoader } from './threejs/jsm/loaders/GLTFLoader.js';
    import { RGBELoader } from './threejs/jsm/loaders/RGBELoader.js';
    import { RoughnessMipmapper } from './threejs/jsm/utils/RoughnessMipmapper.js';
    import { AfterimagePass } from './threejs/jsm/postprocessing/AfterimagePass.js';
    import { SobelOperatorShader } from './threejs/jsm/shaders/SobelOperatorShader.js';
    import { ShaderPass } from './threejs/jsm/postprocessing/ShaderPass.js';

    import { UnrealBloomPass } from './threejs/jsm/postprocessing/UnrealBloomPass.js';
    const params = {
        exposure: 1,
        bloomStrength: 1.5,
        bloomThreshold: 0,
        bloomRadius: 0
    };

    import {
        DirectionalLight,
        DirectionalLightHelper,
        HemisphereLight,
        HemisphereLightHelper
    } from './build/three.module.js';



    let gltfpath ='./gltf/jp/'
    let gltfurl ="scene.gltf"


    // Helper为灯关的辅助线方便调试

    //射线检测

    let colorIndex =0
    let colorArr =["#E8C279","#130AF2","#C5B49A","#6A5ACD","#AA4631"]

    //	color: 0x77F28F,



    let oldSelect,oldMaterial,clock,mixer ;

    let camera, scene, renderer,floor,directionalLight,gltfobj,controls,stats,composerAll;

    init();
    //doinitLight()
    dolight()
    //dodiban()
    //	doAxsHelper()
    render();

    $(function(){

        $(".color").click(function(){

            colorIndex=$(this).index()
        })

    })
    // // 初始化灯光
    // function doinitLight() {
    // 	var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.3 );//模拟远处类似太阳的光源
    // 	directionalLight.color.setHSL( 0.1, 1, 0.95 );
    // 	directionalLight.position.set( 0, 200, 0).normalize();
    // 	scene.add( directionalLight );
    //
    // 	var ambient = new THREE.AmbientLight( 0x404040 ); //AmbientLight,影响整个场景的光源
    // 	ambient.position.set(30,30,30);
    // 	scene.add( ambient );
    // }
    function dolight(){

        directionalLight = new DirectionalLight(0xffffff, 0.5);
        directionalLight.position.set(-4, 8, 4);
        let dhelper = new DirectionalLightHelper(directionalLight, 5, 0xff0000);

        let hemisphereLight = new HemisphereLight(0xffffff, 0xffffff, 0.4);
        hemisphereLight.position.set(0, 8, 0);
        let hHelper = new HemisphereLightHelper(hemisphereLight, 5);

        scene.add(directionalLight);
        scene.add(hemisphereLight);

        // 光源开启阴影
        directionalLight.castShadow = true;
        directionalLight.shadow.mapSize = new THREE.Vector2(1024, 1024);

    }
    function doAxsHelper(){

        let axs  = new THREE.AxesHelper(1000)
        scene.add(axs)
    }

    function init() {
        dostats()

        const container = document.createElement( 'div' );
        document.body.appendChild( container );

        camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1,1000 );
        camera.position.set( -10, 8, 9 );

        scene = new THREE.Scene();
        // scene.background=new THREE.Color( "#353535" );
        const loader = new GLTFLoader().setPath(gltfpath );


        renderer = new THREE.WebGLRenderer( { antialias: true } );
        renderer.setPixelRatio( window.devicePixelRatio );
        renderer.setSize( window.innerWidth, window.innerHeight );
        renderer.toneMapping = THREE.ACESFilmicToneMapping;
        renderer.toneMappingExposure = 1;
        renderer.outputEncoding = THREE.sRGBEncoding;

        // 首先渲染器开启阴影
        renderer.shadowMap.enabled = true;

        // 模型Mesh开启阴影
        container.appendChild( renderer.domElement );

        composerAll = new EffectComposer( renderer );

        const pmremGenerator = new THREE.PMREMGenerator( renderer );
        pmremGenerator.compileEquirectangularShader();
        clock = new THREE.Clock();
        controls = new OrbitControls( camera, renderer.domElement );
        controls.addEventListener( 'change', render ); // use if there is no animation loop
        controls.autoRotate = true;//是否自动旋转
        controls.autoRotateSpeed = 0.5;//自动旋转速度，正比
        controls.update();

        new GLTFLoader().load( '../three/three.js/examples/models/gltf/PrimaryIonDrive.glb', function ( gltf ) {

            const model = gltf.scene;

            scene.add( model );

            mixer = new THREE.AnimationMixer( model );
            const clip = gltf.animations[ 0 ];
            mixer.clipAction( clip.optimize() ).play();

            render();

        } );


        const renderScene = new RenderPass( scene, camera );

        const bloomPass = new UnrealBloomPass( new THREE.Vector2( window.innerWidth, window.innerHeight ), 1.5, 0.4, 0.85 );
        bloomPass.threshold = params.bloomThreshold;
        bloomPass.strength = params.bloomStrength;
        bloomPass.radius = params.bloomRadius;

        composerAll = new EffectComposer( renderer );
        composerAll.addPass( renderScene );

        composerAll.addPass( bloomPass );

        window.addEventListener( 'resize', onWindowResize, false );

    }

    function onWindowResize() {

        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();

        renderer.setSize( window.innerWidth, window.innerHeight );

        render();

    }


    function dodiban(){

        let floorGeometry = new PlaneGeometry(200, 200, 1);
        let floorMaterial = new MeshPhongMaterial({
           	color: 0x77F28F,
            //   color:  colorArr[colorIndex],
            shininess: 0,
            // wireframe: true
        });
        floor = new Mesh(floorGeometry, floorMaterial);
        floor.rotation.x = -0.5 * Math.PI;
        floor.position.y = -2.1;

        // 地板接受阴影开启
        floor.receiveShadow = true;
        scene.add(floor);
    }


    // 点击部件
    function  dobujian(gltf){
        console.log("点击部件")
        let raycaster = new THREE.Raycaster();

        let mouse = new THREE.Vector2();

        const selectHandler = function (ev) {
            mouse.x = (ev.clientX / window.innerWidth) * 2 - 1;
            mouse.y = -(ev.clientY / window.innerHeight) * 2 + 1;

            raycaster.setFromCamera(mouse, camera);

            // 这里我们只检测模型的选中情况
            let intersects = raycaster.intersectObjects(gltf.scene.children, true);


            if (intersects.length > 0) {
             //   console.log(intersects)
                let selectedObjects = intersects[0].object;
                changecolor(selectedObjects)
            }
        }


        let composer = new EffectComposer(renderer);
        let renderPass = new RenderPass(scene, camera);
        composer.addPass(renderPass);

        let outlinePass = new OutlinePass(new THREE.Vector2(window.innerWidth, window.innerHeight), scene, camera);
        composer.addPass(outlinePass);


        const render = function () {
            requestAnimationFrame(render);
            composer.render();
        }

        outlinePass.visibleEdgeColor.set('#130AF2'); // 选中颜色
        outlinePass.edgeStrength = 5;
        outlinePass.edgeGlow = 1.5;

        document.body.addEventListener('click', selectHandler, false);
    }


    function changecolor(selectedObjects){
        let newMaterial = selectedObjects.material.clone();

        let oldMaterialObj  = selectedObjects.material.clone();


        console.log("objjjjjjjjjjj")
        let color = newMaterial.color
        console.log(color)
        console.log(newMaterial)
        if(oldSelect && oldMaterial){
            console.log( oldMaterial )

            if(oldSelect.uuid == selectedObjects.uuid){
                console.log("龍王廟")
                newMaterial = oldMaterial
           //     newMaterial.color
                console.log(  newMaterial.color )
                oldMaterial = ''
                oldSelect = ''
            }else{

                oldSelect.material = oldMaterial
                oldMaterial = ''
                oldSelect = ''
                oldSelect =  selectedObjects
                oldMaterial = oldMaterialObj
                console.log("第2次點擊")
                newMaterial.color =  new THREE.Color(colorArr[colorIndex]); //重新修改颜色
                console.log(  newMaterial.color )
            }

        }else{
            oldSelect =  selectedObjects
            oldMaterial = oldMaterialObj
            console.log("第一次點擊")
            newMaterial.color =  new THREE.Color(colorArr[colorIndex]); //重新修改颜色
            console.log(  newMaterial.color )
        }


        console.log("obbbbbbbjjjj")
        console.log(selectedObjects)

      //  selectedObjects.material = newMaterial;
        render()
    }

    //


    //内存  帧数 仪表
    function dostats(){
        stats = new Stats();
        document.body.appendChild( stats.dom );

    }

    function render() {
        composerAll.render();
        const delta = clock.getDelta();

        const time = Date.now() * 0.00008;
        //
        // camera.position.x = Math.sin( time ) * 500;
        // camera.position.z = Math.cos( time ) * 500;
        // camera.lookAt( scene.position );
       // requestAnimationFrame(render)
    //    renderer.render( scene, camera );
        stats.update()

    }

</script>

</body>
</html>
